package p2pscrabble;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;

import javax.swing.Timer;

import javax.swing.JLabel;
import javax.swing.JPanel;

public class TimerPanel extends JPanel implements ActionListener {
	Timer[] timer;
	JLabel[] timerText;

	long[] remaining;
	long lastUpdate;

	NumberFormat format;
	boolean IamPlayer1;
	int timerNow;

	public TimerPanel(boolean myTurn, boolean isHost) {
		remaining = new long[2];
		remaining[0] = 10 * 60 * 1000;
		remaining[1] = 10 * 60 * 1000;

		format = NumberFormat.getNumberInstance();
		format.setMinimumIntegerDigits(2);

		timerText = new JLabel[2];
		timerText[0] = new JLabel("10:00");
		timerText[1] = new JLabel("10:00");

		timer = new Timer[2];
		timer[0] = new Timer(1000, this);
		timer[1] = new Timer(1000, this);

		IamPlayer1 = isHost;
		timerNow = (myTurn && isHost) || (!myTurn && !isHost) ? 0 : 1;

		start();

		//add(timerText[0]);
		//add(timerText[1]);
	}

	public void start() {
		lastUpdate = System.currentTimeMillis();
		timer[timerNow].start();
	}

	public void changeTurn() {
		long now = System.currentTimeMillis();

		remaining[timerNow] -= now - lastUpdate;
		timer[timerNow].stop();
		timerNow = (timerNow + 1) % 2;

		start();
	}

	public void setTurn(int player) {
		long now = System.currentTimeMillis();
		remaining[timerNow] -= now - lastUpdate;
		timer[timerNow].stop();
		
		timerNow = player;
		start();
	}

	void updateDisplay() {
		long now = System.currentTimeMillis(); // current time in ms
		long elapsed = now - lastUpdate; // ms elapsed since last update
		remaining[timerNow] -= elapsed; // adjust remaining time
		lastUpdate = now; // remember this update time

		// Convert remaining miliseconds to mm:ss format and display
		if (remaining[timerNow] < 0)
			remaining[timerNow] = 0;
		int minutes = (int) (remaining[timerNow] / 60000);
		int seconds = (int) ((remaining[timerNow] % 60000) / 1000);

		timerText[timerNow].setText(format.format(minutes) + ":"
				+ format.format(seconds));

		// If we've completed the countdown beep and display new page
		if (remaining[timerNow] == 0) {
			// Stop updating now.
			// timer[timerNow].stop();
			// end game
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		updateDisplay();
	}

	public long getMyRemaining() {
		return IamPlayer1 ? remaining[0] : remaining[1];
	}

	public void setOppTimer(long oppTime) {
		int i = IamPlayer1 ? 1 : 0;
		remaining[i] = oppTime;
		updateDisplay();
	}
}